import React, { useState } from 'react';
import styles from '../index.less';
import { Tooltip } from 'antd';

import { CaretLeftOutlined, CaretRightOutlined, InfoCircleOutlined } from '#/utils/antdIcons.js';
import { PageLoading, TRDefault } from '@/components';
import { TjChart } from '@/pages/ETrade/components';
import { useRem } from '@/hooks';
import { monthChart, monthPieDic } from '../helper';
import BaseTable from './BaseTable';

export const MonthContent = ({ loading, dataSource = [], dataHeader = [], pieData = {} }) => {
  useRem(1920);

  const [isFullScreenEcharts, setIsFullScreenEcharts] = useState(false); // 是否为图表全屏展示

  const [isFullScreenTable, setIsFullScreenTable] = useState(false); // 是否为表格全屏展示

  const getClassName = () => {
    let classNameEcharts = styles.charts;
    let classNameTable = styles.table;
    if (isFullScreenEcharts) {
      classNameEcharts = `${styles.charts} ${styles.chartsFullWidth}`;
      classNameTable = `${styles.table} ${styles.tableNoWidth}`;
    } else if (isFullScreenTable) {
      classNameEcharts = `${styles.charts} ${styles.chartsNoWidth}`;
      classNameTable = `${styles.table} ${styles.tableFullWidth}`;
    }

    return {
      classNameEcharts,
      classNameTable,
    };
  };

  const getChartOption = (obj, arr, index) => {
    if (index === 0) {
      const data = [];
      let total = 0;
      for (let k in monthPieDic) {
        total += pieData[k];
        data.push({
          name: monthPieDic[k],
          value: pieData[k],
          ...(monthPieDic[k] === '风电' ? { selected: true } : {}),
        });
      }
      obj.series.map((i) => {
        i.data = data;
      });
      total = total && total.toFixed(2);
      obj.title.text = `总收入:${total}`;
      obj.legend.formatter = function (name) {
        let value = 0;
        data.forEach((i) => {
          if (i.name === name) {
            value = i.value;
          }
        });
        return `${name} ${value}`;
      };
    } else if (index === 1) {
      const keys = ['XAXIS', 'totalSaleQuantity', 'avgPrice'];
      const source = [];
      arr.forEach((i) => {
        if (i.code) {
          const v = {};
          keys.forEach((k) => {
            v[k] = k === 'XAXIS' ? i.name : Number(i.data ? i.data[k] : 0);
          });
          source.push(v);
        }
      });
      obj.xAxis = [{ type: 'category' }];
      obj.dataset = {
        dimensions: keys,
        source: source,
      };
      obj.series = [
        {
          name: '总销售电量',
          color: '#5795CD',
          dataIndex: 'totalSaleQuantity',
          type: 'bar',
        },
        {
          name: '平均电价',
          color: '#E6E963',
          dataIndex: 'avgPrice',
          props: {
            symbol: 'circle',
            yAxisIndex: 1,
          },
          type: 'line',
        },
      ];
    }
    return obj;
  };

  const highlightWind = (chartRef) => {
    //获取当前series中data长度，后面遍历取消高亮
    let dataCount = 3;
    // 设置默认展示，seriesIndex：系列名，dataIndex：当前索引
    chartRef.dispatchAction({
      type: 'highlight',
      name: '风电',
    });
    // 鼠标进入高亮当前，取消其他高亮
    chartRef.on('mouseover', (e) => {
      chartRef.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: e.dataIndex,
      });
      // 根据当前option中data的length，遍历取消其他高亮
      for (let i = 0; i < dataCount; i++) {
        if (i !== e.dataIndex) {
          chartRef.dispatchAction({
            type: 'downplay',
            seriesIndex: 0,
            dataIndex: i,
          });
        }
      }
    });
    //鼠标移出后显示之前默认高亮的那块，其他取消高亮
    chartRef?.on('mouseout', (e) => {
      chartRef?.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: 0,
      });
      if (e.dataIndex !== 0) {
        chartRef?.dispatchAction({
          type: 'downplay',
          seriesIndex: 0,
          dataIndex: e.dataIndex,
        });
      } else {
        chartRef?.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: 0,
        });
      }
    });
  };

  const _getEchartsData = () => {
    if (dataSource.length === 0) return <TRDefault type={'empty'} />;
    return (
      <div className={styles.chartsRender}>
        {monthChart.map((t, i) => {
          return (
            <div
              key={i}
              style={{
                height: `calc(${Math.floor(100 / monthChart.length)}%)`,
                minHeight: 204,
              }}
            >
              <div className={styles.chartTitle}>
                {t['chartName']}
                {i === 0 && <div className={styles.unit}>单位: 万元</div>}
              </div>
              <div style={{ height: `calc(100% - 30px)` }}>
                {i === 0 ? (
                  <TjChart
                    group={'A' + i}
                    callBack={highlightWind}
                    option={getChartOption(t, dataSource, i)}
                  />
                ) : (
                  <TjChart group={'A' + i} option={getChartOption(t, dataSource, i)} />
                )}
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  if (loading) return <PageLoading />;
  return (
    <>
      <div className={styles.content}>
        <div className={getClassName().classNameEcharts}>
          {_getEchartsData()}
          <div
            className={styles.leftArrow}
            onClick={() => {
              setIsFullScreenEcharts(!isFullScreenEcharts);
            }}
          >
            {isFullScreenEcharts ? <CaretLeftOutlined /> : <CaretRightOutlined />}
          </div>
        </div>
        <div className={getClassName().classNameTable}>
          <div
            className={styles.rightArrow}
            onClick={() => {
              setIsFullScreenTable(!isFullScreenTable);
            }}
          >
            {isFullScreenTable ? <CaretRightOutlined /> : <CaretLeftOutlined />}
          </div>
          <div className={styles.tableScroll}>
            <div className={styles.box1}>
              <div className={styles.hint}>
                <h3>现货交易月报</h3>
                <Tooltip
                  placement={'bottomLeft'}
                  title={
                    <div>
                      <div>1.基数电量为上网电量口径，包括新能源保障利用小时电量；</div>
                      <div>
                        2.中长期合约电量不含基数电量，含省内直接交易、跨省区直接交易、合同转让交易等各类交易电量；
                      </div>
                      <div>
                        3.此表填报单位包括所有参与现货交易的发电企业，新能源按统计口径法人单位填报，如同一单位有两类及以上装机，细化数据到装机类型。
                      </div>
                      <div>
                        4.容量补偿费用、调频等辅助交易费用、市场分摊返还费用等如当月尚未发布，能量化预估的预估填报。
                      </div>
                      <div>
                        5.其他费用收入，分摊返还费用包括调频等辅助费用，考核等支出类计为负，补偿等收入类计为正。
                      </div>
                    </div>
                  }
                >
                  <InfoCircleOutlined style={{ color: '#2978FB' }} className={styles.tooltip} />
                </Tooltip>
              </div>
            </div>
            {dataSource.length > 0 ? (
              <BaseTable
                props={{
                  tableData: dataSource,
                  tableHead: dataHeader,
                }}
              />
            ) : (
              <TRDefault type="empty" />
            )}
          </div>
        </div>
      </div>
    </>
  );
};
